package org.vectrics.recruiter.struts.admin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.jsp.JspException;

import org.vectrics.SystemException;
import org.vectrics.common.util.DateUtil;
import org.vectrics.common.util.StringUtils;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;
import org.vectrics.user.PersonCommunication;
import org.vectrics.user.PersonCommunicationMethod;
import org.vectrics.user.PersonCommunicationMethodType;
import org.vectrics.user.PersonCommunicationReason;
import org.vectrics.user.PersonCommunicationReasonType;
import org.vectrics.user.PersonEncounterStatusType;

public class SavePersonPhoneCallAction extends VectricsStrutsAction {

	/**
	 * Save person communication.
	 */
	@Override
	protected String doExecute(VectricsActionData actionData) throws JspException {
		PersonPhoneCallForm form = (PersonPhoneCallForm)actionData.getForm();
		if (form.getToPersonId()!=null){
			actionData.getRequest().setAttribute("personId", form.getToPersonId());			
		}
		if (actionData.wasButtonPressed("cancel") == false) {
			log.info("encountStatusCode=" + form.getEncounterStatusCode());
			log.info("personId=" + form.getFromPersonId());
			log.info("personCommunicationId=" + form.getId());
						
			Person leadPerson = CoreServiceLocator.getPersonService().findPersonById(new Long(form.getFromPersonId()));
			Person toPerson = CoreServiceLocator.getPersonService().findPersonById(new Long(form.getToPersonId()));
			PersonCommunication communication = null;
			if (StringUtils.isNullOrBlank(form.getId())) {
				communication = new PersonCommunication();
			} else {
				communication = CoreServiceLocator.getPersonService().findPersonCommunication(new Long(form.getId()));
			}
			
			communication.setPerson(toPerson);
			communication.setLeadPerson(leadPerson);
			communication.setDirection(PersonCommunication.DIRECTION_TO);
			PersonEncounterStatusType doneStatus = CoreServiceLocator
				.getPersonService().findPersonEncounterStatusType(form.getEncounterStatusCode());
			if (doneStatus == null) {
				throw new SystemException("Could not find encounter status type: " + form.getEncounterStatusCode());
			}
			communication.setEncounterStatus(doneStatus);
			
			PersonCommunicationMethodType methodType = CoreServiceLocator.getPersonService()
				.findPersonCommunicationMethodType(PersonCommunicationMethodType.TYPE_PHONE_CALL);
			if (methodType == null)
				throw new SystemException("Could not find communication method");
			PersonCommunicationMethod method = new PersonCommunicationMethod();
			method.setPersonCommunicationMethodType(methodType);
			communication.setMethod(method);
			SimpleDateFormat format = CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(actionData.getLocale());
			
			log.debug("Find paramaters that are reasons selected for the communication");
			communication.getPersonCommunicationReasons().clear();
			Collection<String> reasonParameters = this.getParametersWithPrefix(actionData.getRequest(), "reason_");
			Iterator<String> iter = reasonParameters.iterator();
			while (iter.hasNext()) {
				String parameterName = iter.next();
				String paramValue = actionData.getRequest().getParameter(parameterName);
				log.info("Reason param value: " + paramValue);
				if (paramValue != null) {
					String reasonCode = parameterName.substring("reason_".length());
					log.info("Found Parameter for reason code: " + reasonCode);
					
					PersonCommunicationReasonType reasonType =
						CoreServiceLocator.getPersonService().findPersonCommunicationReasonType(reasonCode);
					PersonCommunicationReason commReason = new PersonCommunicationReason();
					commReason.setPersonCommunication(communication);
					commReason.setPersonCommunicationReasonType(reasonType);
					communication.getPersonCommunicationReasons().add(commReason);
				}
			}

			String startDateString = form.getStartDate();
			Date startDate = null;
			if (!startDateString.equals("")) {
				try {
					startDate = format.parse(startDateString);
		
					int hour = Integer.parseInt(form.getStartHour());
					int minute = Integer.parseInt(form.getStartMinute());
					log.info("Start hour: " + hour + "  Start minute: " + minute);
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(startDate);
					calendar.add(Calendar.HOUR, hour);
					calendar.add(Calendar.MINUTE, minute);
					
					if (form.getStartAmPm() != null) {
						if (form.getStartAmPm().equals("pm")) {
							calendar.set(Calendar.AM_PM, Calendar.PM);
						} else {
							calendar.set(Calendar.AM_PM, Calendar.AM);
						}
					}
					communication.setDateStart(calendar.getTime());
					startDate = communication.getDateStart();
				} catch (ParseException pe) {
					throw new SystemException("Exception parsing start date");
				}
			} 
			
			String minutos = form.getMinutes();
			if (!minutos.equals("")) {
				Integer minutes = new Integer(minutos);
				long endTime = startDate.getTime() + (minutes.intValue() * 60 * 1000);
				Date endDate = new Date(endTime);
				communication.setDateEnd(endDate);
			} 
			communication.setNotes(form.getNotes());
			
			CoreServiceLocator.getPersonService().updatePersonCommunication(communication);
			log.info("Done saving, return forward=success");
			return "success";
		} else {
			log.info("Cancel button pressed");
			return "cancel";
		}
	}
	
}
